import sqlite3
import os, shutil

from colorama import init,Fore
init(autoreset=True)

try:
    # Open the meta file
    print("Finding meta database file... ", end='')
    try:
        f=open("./meta")
        f.close
    except Exception as e:
        print(Fore.RED+"Error:", e ,". Is the meta file exist?")
        raise
    else:
        print(Fore.GREEN+"Success.")

    # Connect the database
    print("Trying connecting to the database... ", end='')
    try:
        conn = sqlite3.connect("./meta")
        c = conn.cursor()
    except Exception as e:
        print(Fore.RED+"Error:", e)
        raise
    else:
        print(Fore.GREEN+"Success.")

    # Set the extra folder
    print("Set the extra folders... ", end='')
    try:
        c.execute("SELECT n from a")
        res = c.fetchall()
        for f in res:
            f = f[0]
            if f[0]=="/" and f[1]=="/" :
                continue
            for i in range(len(f)):
                l = len(f)
                if f[l-i-1]=="/":
                    f = f[:l-i]
                    if not os.path.exists("./sorted_resource/"+f):
                        print("\rSet the extra folders...  "+" "*80, end='')
                        print('''\rSet the extra folders...  '''+f, end='')
                        os.makedirs("./sorted_resource/"+f)
                    break
    except Exception as e:
        print(Fore.RED+"Error:", e)
        raise
    else:
        print("\rSet the extra folders...  "+" "*80, end='')
        print("\rSet the extra folders...  "+Fore.GREEN+"Success.")

    # Rename and Move
    print("Renaming and moving the resource file... ", end='')
    try:
        c.execute("SELECT n,h from a")
        res = c.fetchall()
        k = 1
        isskip = False
        for r in res:
            f = r[0]
            hash = r[1]
            for i in range(len(f)):
                l = len(f)
                if f[l-i-1]=="/":
                    name = f[l-i:]
                    fileLocate = f[:l-i]
                    try:
                        if f[0]=="/" and f[1]=="/" :
                            os.rename("./dat/"+hash[0:2]+"/"+hash, "./dat/"+hash[0:2]+"/"+name)
                            shutil.move("./dat/"+hash[0:2]+"/"+name, "./sorted_resource/"+name)
                        else:
                            os.rename("./dat/"+hash[0:2]+"/"+hash, "./dat/"+hash[0:2]+"/"+name)
                            shutil.move("./dat/"+hash[0:2]+"/"+name, "./sorted_resource/"+fileLocate+"/"+name)
                    except Exception as e:
                        print('''\rRenaming and moving the resource file...  '''+Fore.RED+"Error:"+str(e))
                        if not isskip:
                            answer = input("Will you want to continue?[If you want to ignore the warns, please enter S]  (Y/N/S) ")
                            if answer == "S" or answer == "s" :
                                isskip = True
                            elif not (answer == "Y" or answer == "y") :
                                os._exit(0)
                    finally: 
                        print('''\rRenaming and moving the resource file...  '''+' '*60+"(%d/%d)"%(len(res),k), end='')
                        print('''\rRenaming and moving the resource file...  '''+name+"  (%d/%d)"%(len(res),k), end='')
                        k += 1
                    break
    except Exception as e:
        print(Fore.RED+"Error:", e)
        raise
    else:
        print("\rRenaming and moving the resource file...  "+" "*75, end='')
        print("\rRenaming and moving the resource file...  "+Fore.GREEN+"Success.")


    conn.close()
except Exception as e:
    conn.close()
    print(Fore.RED+"\nProgram met a fatal error, please check the integrity of the file and restart the program.\n")

os.system("pause")